package 文件IO.文件搜索案例_查文件名匹配;

import java.io.File;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //1.输入关键词
        Scanner sc = new Scanner(System.in);
        System.out.print("输入文件目录: ");
        String rootPath = sc.next();
        System.out.println();
        System.out.println("输入查找的关键词: ");
        String searchWord = sc.next();
        System.out.println();

        //2.构建File对象，检查是否合法
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()) {
            System.out.println("路径不合法");
            return;
        }

        //3.递归搜索
        SearchFile(rootFile,searchWord);
    }
    public static void SearchFile(File rootFile,String searchWord){
        //1.判断当前目录有哪些内容
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }
        //2.遍历每个目录的内容
        for(File f : files){
            if(f.isFile()){
                //是普通文件
                String fileName = f.getName();
                if(fileName.contains(searchWord)){
                    System.out.println("找到:"+f.getAbsoluteFile());
                }
            }else if(f.isDirectory()){
                SearchFile(f,searchWord);
            }
        }
    }
}
